package com.lanou.controller;

import com.lanou.bean.Person;
import com.lanou.mapper.PersonMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.rmi.activation.UnknownObjectException;

/**
 * Created by dllo on 18/3/7.
 */
@Controller
public class MainController {
    @Resource private PersonMapper personMapper;

    @RequestMapping("/home")
    public String pageHome() {
        return "home";
    }

    @RequestMapping("/login")
    public String loginpage() {
        if(SecurityUtils.getSubject().isAuthenticated()){
            return "redirect:home";
        }else{

            return "login";
        }
    }

    @RequestMapping("/loginsubmit")
    public String loginsubmit(HttpServletRequest request) throws Exception {
        //因为表单过滤器的原因，这个方法不需要接收用户名和密码，在进行Login
        //而是由过滤器直接把用户名密码交给realm来做认证
        //我们在这个方法中，就只处理异常就可以
        //过滤器先于servlet执行，所以当在realm中处理认证时出现异常 过滤器会把异常信息保存到request中发给servlet，即交给我们来处理

        //1.获取异常的名字
        String exName = (String) request.getAttribute("shiroLoginFailure");

        if(UnknownObjectException.class.getName().equals(exName)){
            throw new UnknownAccountException("账号不存在");
        }else if(IncorrectCredentialsException.class.getName().equals(exName)){
            throw new IncorrectCredentialsException("密码错误");
        }else{
            throw new Exception("未知错误");
        }

    }
//    @RequiresRoles("CO")
    @RequestMapping("/test")
    public String pageTest(){
        if (SecurityUtils.getSubject().hasRole("CO")){
        return "test";}
        else {
            return "redirect:home";
        }
    }

    @ResponseBody
    @RequestMapping("/pertest")
    public Person perinfo(){
        return personMapper.selectById(1);
    }

}
